package com.example.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;

/**
 * @author DestinyCc
 * @date 2022/4/19
 * python脚本执行工具，返回python脚本执行结果最后一行
 * 使用方法：PythonScriptCallable callable = new PythonScriptCallable(cmd);
 *           FutureTask<String> pythonTask = new FutureTask<>(callable);
 *           pythonTask.run();
 *           while (!pythonTask.isDone()){
 *              //Thread.sleep(1000);
 *           }
 *           String result = pythonTask.get();
 */
@Slf4j
public class PythonScriptCallable implements Callable<String> {
    private String cmd;

    public PythonScriptCallable(String cmd){
        this.cmd = cmd;
    }

    @Override
    public String call() throws Exception {
        Process process = Runtime.getRuntime().exec(this.cmd);
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        String result = null;
        while ((line = in.readLine()) != null) {
            log.info("{}", line);
            result = line;
        }
        process.waitFor();
        in.close();
        return result;
    }
}
